const formatTime = date => {
	const year = date.getFullYear()
	const month = date.getMonth() + 1
	const day = date.getDate()
	const hour = date.getHours()
	const minute = date.getMinutes()
	const second = date.getSeconds()

	return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
	n = n.toString()
	return n[1] ? n : `0${n}`
}

var util = {};
util.baseurl = 'https://xcx.cwepc.cn/api/';
// util.baseurl = 'http://localhost:801/api/';
util.url = {
	'getToken': util.baseurl + 'index/get_token',
	'getUser': util.baseurl + 'user/get',
	'uploadImg': util.baseurl + 'common/upload',
};
//小程序登录，获取token
util.getToken = function () {
	var token = wx.getStorageSync('token');
	if (token == '') {
		const obj = wx.getLaunchOptionsSync()
		return new Promise(function (resolve, reject) {
			wx.login({
				success: res => {
					wx.request({
                        url: util.url.getToken,
						data: {
							code: res.code,
							path: obj.path,
							scene: obj.scene
						},
						success: function (res) {
                            console.log(res);
							if (res.data.res_code == 301) {
								wx.setStorageSync('token', '');
								// wx.navigateTo({
								// 	url: '/pages/perfect/pages/login/index',
								// })
								return;
							}
							if (res.data.errno != 0) {
								wx.showModal({
									title: '提示',
									content: res.data.msg,
								})
								reject();
							} else {
								wx.setStorageSync('token', res.data.token);
								resolve(res.data.token);
							}
						},
					})
				}
			})
		});
	} else {
		return new Promise(function (resolve, reject) {
			resolve(token);
		});
	}
};
//是否注册会员
util.getUser = async function (P_account_id) {
    let token = await this.getToken();

    // console.log(token);
    let data={};
    if(P_account_id > 0){
        data = {
            account_id:P_account_id
        }
    }
	return new Promise(function (resolve, reject) {
		wx.request({
			url: util.url.getUser,
			method: 'POST',
			header: {
				'content-type': 'application/x-www-form-urlencoded',
				'token': token
            },
            data:data,
			success: function (userInfo) {
				console.log(userInfo);
				if (userInfo.data.errno != 0) {
					wx.showModal({
						title: '提示',
						content: userInfo.data.msg,
					})
					wx.setStorageSync('user_name', '-');
					wx.setStorageSync('avatar', '-');
					wx.setStorageSync('share_code', '-');
				}
				//当前人的id 存入缓存中
				if (typeof userInfo.data.data != 'undefined') {
					wx.setStorageSync('account_id', userInfo.data.data.userInfo.id);
				}
				resolve(userInfo.data.data);
			}
		});
	});
};

util.uploadfile = function (file, data) {
	console.log(util.url.uploadImg);
	return new Promise(function (resolve, reject) {
		wx.uploadFile({
			url: util.url.uploadImg,
			filePath: file,
			name: 'file',
			formData: data,
			header: {
				'content-type': 'multipart/form-data'
			},
			success(res) {
				let rt = JSON.parse(res.data)
				resolve(rt);
			}
		})
	});
};


//封装request
util.request = function (option) {
	var token = wx.getStorageSync('token');
	var url = util.baseurl + option.url;
	var option = option ? option : {};
	option.showLoading = typeof option.showLoading != 'undefined' ? option.showLoading : true;
	if (option.showLoading) {
		wx.showNavigationBarLoading();
		wx.showLoading({
			title: '加载中'
		});
	}
	// console.log(token);
	return new Promise(function (resolve, reject) {
		wx.request({
			url: url,
			method: option.method ? option.method : 'POST',
			data: option.data ? option.data : {},
			header: {
				'content-type': 'application/x-www-form-urlencoded',
				'token': token
			},
			success(res) {
				if (option.showLoading) {
					wx.hideNavigationBarLoading();
					wx.hideLoading();
				}
				if (res.data.errno == '0') {
					resolve(res.data.data)
				} else if (res.data.errno == '41009') {
					// 清空登录状态
					wx.setStorageSync('token', '');
					return;
				} else {
					// 弹出提示信息
					if (res.data.msg) {
						util.message(res.data.msg, '', 'error');
					}
					reject(res.data)
					// 强制登录
					if (res.data.res_code == 301) {
						wx.setStorageSync('token', '');
						wx.navigateTo({
							url: '/pages/perfect/pages/login/index',
						})
						return;
					}
				}
			},
			fail(err) {
				reject(err)
			}
		})
	});
};

util.message = function (title, redirect, type) {
	if (!title) {
		return true;
	}
	if (typeof title == 'object') {
		redirect = title.redirect;
		type = title.type;
		title = title.title;
	}
	if (redirect) {
		var url = '',
			redirectFunction = '';
		if (redirect.indexOf("na:") > -1) {
			redirectFunction = 'navigateTo';
			url = redirect.substring(3);
		} else if (redirect.indexOf("re:") > -1) {
			redirectFunction = 'redirectTo';
			url = redirect.substring(3);
		} else if (redirect.indexOf("sw:") > -1) {
			redirectFunction = 'switchTab';
			url = redirect.substring(3);
		} else if (redirect.indexOf("ba:") > -1) {
			redirectFunction = 'navigateBack';
			url = redirect.substring(3);
		} else {
			url = redirect;
			redirectFunction = 'redirectTo';
		}
	}
	if (!type) {
		type = 'success';
	}
	if (type == 'success') {
		wx.showToast({
			title: title,
			icon: 'success',
			duration: 2000,
			mask: url ? true : false,
			complete: function () {
				if (url) {
					setTimeout(function () {
						wx[redirectFunction]({
							url: url,
						});
					}, 1800);
				}

			}
		});
	} else if (type == 'error') {
		wx.showModal({
			title: '系统信息',
			content: title,
			showCancel: false,
			complete: function () {
				if (url) {
					wx[redirectFunction]({
						url: url,
					});
				}
			}
		});
	}
};
/** 
检查session是否过期,更新sessionkey(获取手机号和UNIID时使用)
*/
util.checksession = function () {
	return new Promise(function (resolve, reject) {
		wx.checkSession({
			success: function () {
				console.log('没过期')
				resolve(wx.getStorageSync('token'));
			},
			fail: function () {
				console.log('已过期')
				wx.login({
					success: loginres => {
						wx.request({
							url: util.url.getToken,
							data: {
								code: loginres.code
							},
							success: function (res) {
								if (res.data.errno != 0) {
									wx.showModal({
										title: '提示',
										content: res.data.msg,
									})
									return
								} else {
									wx.setStorageSync('token', res.data.token);
									resolve(res.data.token);
								}
							},
						})
					}
				})
			}
		})
	});
};
util.checkAuth = function (obj) {

	wx.getSetting({
		success: function (res) {
			if (res.authSetting['scope.userInfo']) {
				wx.getUserInfo({
					success: function (res) {
						console.log('已授权');
						// 用户已经授权过,不需要显示授权页面,所以不需要改变 isHide 的值
						obj.setData({
							user_warrant: true,
						});
					}
				});
			} else {
				console.log('未授权');
				// 用户没有授权
				obj.setData({
					user_warrant: false
				});
			}
		}
	});
};

util.observe = (obj, key, watchFun, deep, page) => {
	let val = obj[key];
	if (val != null && typeof val === "object" && deep) {
		Object.keys(val).forEach((item) => {
			observe(val, item, watchFun, deep, page);
		});
	}

	Object.defineProperty(obj, key, {
		configurable: true,
		enumerable: true,
		set: (value) => {
			watchFun.call(page, value, val);
			val = value;
			if (deep) {
				observe(obj, key, watchFun, deep, page);
			}
		},
		get: () => {
			return val;
		}
	});
};

/**
 * @name: 自定义watch 监听属性
 * @author: camellia
 * @date: 2021-11-12
 */
util.setWatcher = (page) => {
	let data = page.data;
	let watch = page.watch;
	Object.keys(watch).forEach((item) => {
		let targetData = data;
		let keys = item.split(".");
		for (let i = 0; i < keys.length - 1; i++) {
			targetData = targetData[keys[i]];
		}
		let targetKey = keys[keys.length - 1];
		let watchFun = watch[item].handler || watch[item];
		let deep = watch[item].deep;
		util.observe(targetData, targetKey, watchFun, deep, page);
	});
};

//订阅模板消息
util.requestMsg = (tmplIds)=> {
	return new Promise((resolve, reject) => {
		wx.requestSubscribeMessage({
			tmplIds: tmplIds,
			success: (res) => {
				console.log(res);
				let _state = null;
				let tpls = [];
				tmplIds.map(function (item) {
					if (res[item] == "accept") {
						_state = "accept";
					}
					if (res[item] === "accept") {
						tpls.push(item)
					}
				});
				if (_state == "accept") {
					var str = JSON.stringify(tpls)
					resolve(str)
				} else {
					resolve('')
				}
			},
			fail(err) {
				reject(err)
			}
		})
	})
};


module.exports = {
	formatTime,
	util
}